<template>
  <ul class="todo-main">
    <Item
      v-for="todoItem in todoList"
      :key="todoItem.id"
      v-bind="todoItem"
      :changeDoneById="changeDoneById"
      :singleDeleteById="singleDeleteById"
    />
  </ul>
</template>

<script>
import Item from "./Item";

export default {
  name: "List",
  components: {
    Item,
  },
  data() {
    return {
      todoList: JSON.parse(localStorage.getItem("todoList") || "[]"),
    };
  },
  methods: {
    changeDoneById(id, done) {
      this.todoList = this.todoList.map((item) => {
        return item.id === id ? { ...item, done } : item;
      });
    },
    singleDeleteById(id) {
      this.todoList = this.todoList.filter((item) => item.id !== id);
    },
  },
  /* 只要 todoList 发生改变我就重新触发获取数据的事件 */
  watch: {
    todoList: {
      deep: true,
      handler(newTodoList) {
        /* 触发获取 todoList 数据的事件 */
        this.$bus.$emit("getTodoList", newTodoList);
        /* 存储 localStorage */
        localStorage.setItem("todoList", JSON.stringify(newTodoList));
      },
    },
  },
  mounted() {
    /* 绑定添加 todo 的事件 */
    this.$bus.$on("addTodo", (todo) => {
      this.todoList.unshift(todo);
    });
    /* 绑定全选/反选事件 */
    this.$bus.$on("selectAll", (done) => {
      this.todoList = this.todoList.map((item) => ({ ...item, done }));
    });
    /* 绑定清除已完成事件 */
    this.$bus.$on("deleteCompleted", () => {
      this.todoList = this.todoList.filter(item => !item.done)
    })

    /* 触发获取 todoList 数据的事件 */
    this.$bus.$emit("getTodoList", this.todoList);
  },
  beforeDestroy() {
    this.$bus.$off(["addTodo", "selectAll", "deleteCompleted"]);
  },
};
</script>

<style scoped>
/*main*/
.todo-main {
  margin-left: 0px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding: 0px;
}

.todo-empty {
  height: 40px;
  line-height: 40px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding-left: 5px;
  margin-top: 10px;
}
</style>